package com.tamecode.resource;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.PathResource;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @Author: LiQiongchao
 * @Date: 2021/8/4 20:35
 */
public class FileSourceExample {

    public static void main(String[] args) throws IOException {

        String filePath = "D:\\WorkSpaces\\practise-projects\\spring-4.x-learn\\chapter04-Ioc\\src\\main\\resources\\conf\\file1.txt";

        // 使用系统文件加载文件
        PathResource res1 = new PathResource(filePath);

        // 使用类路径方式加载
        ClassPathResource res2 = new ClassPathResource("conf/file1.txt");

        // 使用 WritableResource 接口写资源文件
        OutputStream outputStream = res1.getOutputStream();
        outputStream.write("hello \nworld ".getBytes());
        outputStream.close();

        // 使用 Resource 读资源
        InputStream is1 = res1.getInputStream();
        InputStream is2 = res2.getInputStream();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int i;
        while ((i = is1.read()) != -1) {
            baos.write(i);
        }
        System.out.println(baos.toString());

        System.out.println("res1: " + res1.getFilename());
        System.out.println("res2: " + res2.getFilename());

        /*
        hello
        world
        res1: file1.txt
        res2: file1.txt
        * */
    }

}
